/**
 * Promise.all
 */
// Promise.all([
//   new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
//   new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
//   new Promise(resolve => setTimeout(() => resolve(3), 1000))  // 3
// ]).then(console.info); // 1,2,3 当上面这些 promise 准备好时：每个 promise 都贡献了数组中的一个元素

// let urls = [
//   'https://api.github.com/users/iliakan',
//   'https://api.github.com/users/remy',
//   'https://api.github.com/users/jeresig'
// ];
// // 将每个 url 映射（map）到 fetch 的 promise 中
// let requests = urls.map(url => fetch(url));
// // Promise.all 等待所有任务都 resolved
// Promise.all(requests)
//   .then(responses => responses.forEach(
//     response => console.info(`${response.url}: ${response.status}`)
//   ));




// let names = ["iliakan", "remy", "jeresig"];
// let requests = names.map((name) =>
//   fetch(`https://api.github.com/users/${name}`)
// );
// Promise.all(requests)
//   .then((responses) => {
//     // 所有响应都被成功 resolved
//     for (let response of responses) {
//       console.info(`${response.url}: ${response.status}`); // 对应每个 url 都显示 200
//     }

//     return responses;
//   })
//   // 将响应数组映射（map）到 response.json() 数组中以读取它们的内容
//   .then((responses) => Promise.all(responses.map((r) => r.json())))
//   // 所有 JSON 结果都被解析："users" 是它们的数组
//   .then((users) => users.forEach((user) => console.info(user.name)));



/**
 * Promise.allSettled
 */
// let urls = [
//   'https://api.github.com/users/iliakan',
//   'https://api.github.com/users/remy',
//   'https://no-such-url'
// ];

// Promise.allSettled(urls.map(url => fetch(url)))
//   .then(results => { // (*)
//     results.forEach((result, num) => {
//       if (result.status == "fulfilled") {
//         console.info(`${urls[num]}: ${result.value.status}`);
//       }
//       if (result.status == "rejected") {
//         console.info(`${urls[num]}: ${result.reason}`);
//       }
//     });
//   });



/**
 * Promise.race：只等待第一个 settled 的 promise 并获取其结果（或 error）
 */
// Promise.race([
//   new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
//   new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
//   new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
// ]).then(console.info); // 1


/**
 * Promise.any： 只等待第一个 fulfilled 的 promise
 */
Promise.any([
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 1000)),
  new Promise((resolve, reject) => setTimeout(() => resolve(1), 2000)),
  new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).then(console.info); // 1